import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input, message } from "antd";
import "../../flexble";
import "../css/Login.css";
import {
  UserOutlined,
  WechatOutlined,
  AlipayOutlined,
  QqOutlined,
  WeiboOutlined,
} from "@ant-design/icons";
import axiosInstance from "../utils/axiosInstance";
import { AuthContext } from "../utils/AuthContext";
import apiConfigManager from '../../utils/apiConfigManager';

const App = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { login } = useContext(AuthContext);
  var [login_type_key, set_login_type_key] = useState("password");
  const [loading, setLoading] = useState(false);
  const [currentApi, setCurrentApi] = useState('');

  // 获取当前API配置用于调试
  React.useEffect(() => {
    const api = apiConfigManager.getCurrentApi();
    setCurrentApi(api.url);
  }, []);

  // 手机号验证规则
  const phoneValidationRules = [
    { required: true, message: "请输入手机号" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
    },
  ];


  // 邮箱验证规则
  const emailValidationRules = [
    { required: true, message: "请输入邮箱" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
    },
  ];


  // 密码验证规则
  const passwordValidationRules = [
    { required: true, message: "请输入密码" },
    {
      pattern: /^.{6,18}$/,
      message: "密码长度必须在6-18位之间",
    },
  ];


  const onFinish = async (values) => {
    setLoading(true);
    try {
      console.log('登录类型:', login_type_key);
      console.log('表单数据:', values);
      console.log('当前API地址:', currentApi); // 添加调试信息
      
      if (login_type_key == "password") {
        // 验证手机号格式
        if (!values.phone || !/^1[3-9]\d{9}$/.test(values.phone)) {
          message.error("手机号格式错误");
          setLoading(false);
          return;
        }
        
        // 验证密码格式
        if (!values.password || !/^.{6,18}$/.test(values.password)) {
          message.error("密码格式错误，长度必须在6-18位之间");
          setLoading(false);
          return;
        }
        
        let res = await axiosInstance.post("/ltc/login", values);
        console.log("密码登录响应:", res.data);
        if (res.data.code === 200) {
          login(res.data.accessToken);
          message.success(res.data.msg);
          navigate("/main");
        } else {
          message.error(res.data.msg);
        }
      } else if (login_type_key == "code") {
        // 验证手机号格式
        if (!values.phone || !/^1[3-9]\d{9}$/.test(values.phone)) {
          message.error("手机号格式错误");
          setLoading(false);
          return;
        }
        
        let res = await axiosInstance.post("/ltc/login", values);
        console.log("验证码登录响应:", res.data);
        if (res.data.code === 200) {
          login(res.data.accessToken);
          message.success(res.data.msg);
          navigate("/main");
        } else {
          message.error(res.data.msg);
        }
      } else if (login_type_key == "email") {
        // 验证邮箱格式
        if (!values.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
          message.error("邮箱格式错误");
          setLoading(false);
          return;
        }
        
        let res = await axiosInstance.post("/ltc/login", values);
        console.log("邮箱登录响应:", res.data);
        if (res.data.code === 200) {
          login(res.data.accessToken);
          message.success(res.data.msg);
          navigate("/main");
        } else {
          message.error(res.data.msg);
        }
      }
    } catch (error) {
      console.error("登录失败:", error);
      message.error("登录失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const handleGetCode = async () => {
    try {
      if (login_type_key == "code") {
        const phone = form.getFieldValue("phone");
        if (!phone) {
          message.error("请输入手机号");
          return;
        }
        let res = await axiosInstance.post("/ltc/sendcode_login", { phone: phone });
        message.success(res.data.msg);
      } else if (login_type_key == "email") {
        const email = form.getFieldValue("email");
        if (!email) {
          message.error("请输入邮箱");
          return;
        }
        let res = await axiosInstance.post("/ltc/sendcode_login", { email: email });
        message.success(res.data.msg);
      }
    } catch (error) {
      console.error("获取验证码失败:", error);
      message.error("获取验证码失败，请重试");
    }
  };
  return (
    <>
      <div className="login_type_div">
        <span
          className={`login_type ${login_type_key === "password" ? "login_type_active" : ""}`}
          onClick={() => {
            set_login_type_key("password");
          }}
        >
          密码登录
        </span>
        <span
          className={`login_type ${login_type_key === "code" ? "login_type_active" : ""}`}
          onClick={() => {
            set_login_type_key("code");
          }}
        >
          验证码登录
        </span>
        <span
          className={`login_type ${login_type_key === "email" ? "login_type_active" : ""}`}
          onClick={() => {
            set_login_type_key("email");
          }}
        >
          邮箱登录
        </span>
      </div>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ width: "80%", height: "15rem", textAlign: "center" }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        {/* 手机号登录 */}
        {login_type_key == "password" ? (
          <>
            <Form.Item
              label="手机号"
              name="phone"
              rules={phoneValidationRules}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={passwordValidationRules}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item name="remember" valuePropName="checked" label={null}>
              <Checkbox>记住密码</Checkbox>
            </Form.Item>
          </>
        ) : null}

        {/* 手机验证码登录 */}
        {login_type_key == "code" ? (
          <>
            <Form.Item
              label="手机号"
              name="phone"
              rules={phoneValidationRules}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="验证码"
              name="code"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Input style={{ width: "65%" }} />
                <button
                  type="button"
                  className="login_code_button"
                  onClick={handleGetCode}
                >
                  获取验证码
                </button>
              </div>
            </Form.Item>
          </>
        ) : null}

        {/* 邮箱验证码登录 */}
        {login_type_key == "email" ? (
          <>
            <Form.Item
              label="邮箱"
              name="email"
              rules={emailValidationRules}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="验证码"
              name="code"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Input style={{ width: "65%" }} />
                <button
                  type="button"
                  className="login_code_button"
                  onClick={handleGetCode}
                >
                  获取验证码
                </button>
              </div>
            </Form.Item>
          </>
        ) : null}

        <Form.Item label={null}>
          <div style={{ display: "flex", justifyContent: "space-around" }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              onClick={() => {
                navigate("/createuser");
              }}
            >
              注册
            </Button>
          </div>
        </Form.Item>
        <Form.Item label={null}>
          <div className="login_icons_div">
            <UserOutlined className="icons" />
            <WechatOutlined className="icons" />
            <AlipayOutlined className="icons" />
            <QqOutlined className="icons" />
            <WeiboOutlined className="icons" />
          </div>
        </Form.Item>
      </Form>
    </>
  );
};
export default App;
